<template>
  <div class="app-container">
    <sticky class="filter-container">
      <el-row :gutter="20">
        <el-col :span="21">
          <div class="block" style="float: left; margin-right: 3px">
            <el-date-picker
              v-model="datePicker"
              type="datetimerange"
              :picker-options="pickerOptions"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="mini"
              @change="handleSearch"
            />
          </div>
          <el-input
            v-model="listSearch.search"
            placeholder="搜索"
            style="margin-right: 10px;width: 200px"
            class="filter-item"
            size="mini"
            clearable
            @keyup.enter.native="handleSearch"
            @clear="handleSearch"
            @blur="handleSearch"
          />
          <el-select
            v-model="listSearch.is_fast"
            placeholder="阅读"
            clearable
            class="filter-item"
            size="mini"
            style="margin-right: 10px;width: 100px"
            @change="handleSearch"
          >
            <el-option
              v-for="item in enabledTypeOptionsIs_fast"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
          <el-select
            v-model="listSearch.is_timing"
            placeholder="定时"
            clearable
            class="filter-item"
            size="mini"
            style="margin-right: 10px;width: 80px"
            @change="handleSearch"
          >
            <el-option
              v-for="item in enabledTypeOptionsIs_timing"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
          <el-select
            v-model="listSearch.status"
            placeholder="状态"
            clearable
            class="filter-item"
            size="mini"
            style="margin-right: 10px;width: 90px"
            @change="handleSearch"
          >
            <el-option
              v-for="item in enabledTypeOptionsStatus"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
          <el-button
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
          >
            搜索
          </el-button>
          <el-button
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-refresh-right"
            :loading="refreshLoading"
            @click="refresh"
          />
        </el-col>
        <el-col :span="3" style="text-align: right">
          <el-button
            v-if="checkPermission(['admin','article_reading_all', 'article_reading_create'])"
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="showAdd"
          >
            新增
          </el-button>
        </el-col>
      </el-row>
    </sticky>
    <el-table
      border
      :data="list"
      style="width: 100%"
      highlight-current-row
      :default-sort="{ prop: '-time', order: 'descending' }"
      :row-class-name="tableRowClassName"
      @sort-change="sortChange"
    >
      <el-table-column
        label="公众号名称"
        prop="name"
        align="center"
        width="200px"
      />
      <el-table-column
        label="文章标题"
        prop="title"
        align="center"
      />
      <el-table-column
        label="次数"
        prop="number"
        width="80px"
        align="center"
      />
      <el-table-column label="阅读类型" prop="is_fast" width="90px" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.is_fast ? '快速':'按分钟' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="分钟"
        prop="minutes"
        width="80px"
        align="center"
      />
      <el-table-column label="定时" prop="is_timing" width="60px" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_timing ? 'success':'danger'">{{ scope.row.is_timing ? '是':'否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="任务开始时间"
        prop="time"
        align="center"
        width="170px"
        sortable="custom"
      />
      <el-table-column
        label="任务创建时间"
        prop="time_add"
        align="center"
        width="170px"
      />
      <el-table-column
        label="操作"
        width="120px"
        align="center"
      >
        <template slot-scope="scope">
          <el-tooltip v-if="checkPermission(['admin','article_reading_all','article_reading_start']) && scope.row.status === '暂停中' && scope.row.time !== null && scope.row.time > timer" class="item" effect="dark" content="启动" placement="top">
            <el-button
              type="text"
              icon="el-icon-open"
              @click="showStart(scope.row)"
            />
          </el-tooltip>
          <el-tooltip v-else-if="checkPermission(['admin','article_reading_all','article_reading_stop']) && scope.row.status === '运行中' && scope.row.time !== null && scope.row.time > timer" class="item" effect="dark" content="暂停" placement="top">
            <el-button
              type="text"
              icon="el-icon-turn-off"
              @click="showStop(scope.row)"
            />
          </el-tooltip>
          <el-tooltip v-if="checkPermission(['admin','article_reading_all','article_reading_edit'])" class="item" effect="dark" content="编辑" placement="top">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="showEdit(scope.row.id)"
            />
          </el-tooltip>
          <el-tooltip v-if="checkPermission(['admin','article_reading_all','article_reading_delete'])" class="item" effect="dark" content="删除" placement="top">
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      style="text-align: right; margin-top: 20px"
      background
      :hide-on-single-page="true"
      :current-page="listSearch.page"
      :page-size="listSearch.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="listSearch.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 弹框组件 -->
    <vForm :vdialog="dialog" :vtitle="title" :visedit="isedit" :vformid="formid" @changeShow="showUpdate" />
  </div>
</template>

<style>
  .el-table .success-row {
    background: #f0f9eb;
  }
</style>

<script>
// 按钮吸顶
import Sticky from '../../../components/Sticky/index'
// 按钮水波效果
import waves from '../../../directive/waves/waves'
import checkPermission from '@/utils/permission'
import { listArticleReading, startArticleReading, stopArticleReading, delArticleReading } from '@/api/wechat_article_reading'
import vForm from './components/form'

export default {
  components: { Sticky, vForm },
  directives: { waves },
  data() {
    return {
      datePicker: null,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      url_api: process.env.VUE_APP_BASE_API,
      refreshLoading: false,
      downLoading: false,
      listLoading: true,
      timer: '',
      list: [],
      enabledTypeOptionsIs_fast: [
        { key: 'true', display_name: '快速阅读' },
        { key: 'false', display_name: '按分钟' }
      ],
      enabledTypeOptionsIs_timing: [
        { key: 'true', display_name: '是' },
        { key: 'false', display_name: '否' }
      ],
      enabledTypeOptionsStatus: [
        { key: '运行中', display_name: '运行中' },
        { key: '暂停中', display_name: '暂停中' },
        { key: '已过期', display_name: '已过期' }
      ],
      listSearch: {
        total: 0,
        page: 1,
        pageSize: 10,
        ordering: '-time',
        search: '',
        is_fast: '',
        is_timing: '',
        status: '',
        start_date: '',
        end_date: ''
      },
      // 弹出框定义属性
      // （与子组件的 props 属性一致）dialog 控制新增、编辑、查看弹窗的显示与隐藏
      dialog: false,
      title: '',
      isedit: '',
      formid: 0
      // 弹出框定义属性
    }
  },
  mounted() {
    this.timers()
    this.getList()
  },
  methods: {
    // checkPermission 权限检查
    checkPermission,
    // 弹出框
    // 点击按钮事件，显示弹窗组件
    showAdd() {
      this.dialog = true
      this.title = '新增阅读'
      this.isedit = 'add'
    },
    showEdit(row) {
      this.dialog = true
      this.title = '编辑阅读'
      this.isedit = 'edit'
      this.formid = row
    },
    showView(row) {
      this.dialog = true
      this.title = '阅读详情'
      this.isedit = 'view'
      this.formid = row
    },
    // 监听 子组件弹窗关闭后触发，由子组件调用
    showUpdate(val, valid) {
      if (val === 'false') {
        this.dialog = false
        this.formid = valid
      } else {
        this.dialog = true
      }
    },
    // 弹出框
    // 搜索
    handleSearch() {
      // 当页面不在第一页时搜索内容报错
      this.listSearch.page = 1
      this.dateFileter()
      this.getList()
    },
    dateFileter() {
      // 日期时间范围选择
      if (this.datePicker !== null) {
        this.listSearch.start_date = this.datePicker[0]
        this.listSearch.end_date = this.datePicker[1]
      } else {
        this.listSearch.start_date = ''
        this.listSearch.end_date = ''
      }
    },
    // 搜索
    // 排序
    sortChange(column) {
      const { prop, order } = column
      if (order === 'descending') {
        this.listSearch.ordering = `-${prop}`
      } else {
        this.listSearch.ordering = prop
      }
      this.handleSearch()
    },
    // 排序
    // 列表
    getList() {
      this.listLoading = true
      listArticleReading(this.listSearch).then(res => {
        this.list = res.data
        this.listSearch.total = res.count
        this.timers()
        this.listLoading = false
      })
    },
    // 列表
    // 分页
    handleSizeChange(val) {
      this.listSearch.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listSearch.page = val
      this.getList()
    },
    // 分页
    // 刷新
    refresh() {
      this.refreshLoading = true
      this.getList()
      this.refreshLoading = false
      this.$notify.info({
        type: 'info',
        title: '提示',
        message: '已刷新',
        showClose: true,
        duration: 5 * 1000
      })
    },
    // 刷新
    // 计算日期
    timers() {
      var liDate = new Date()
      var year = liDate.getFullYear()
      var month = liDate.getMonth() + 1
      var tdate = liDate.getDate()
      var hours = liDate.getHours()
      var minutes = liDate.getMinutes()
      var seconds = liDate.getSeconds()
      if (tdate < 10) {
        tdate = '0' + tdate
      }
      this.timer = year + '-' + month + '-' + tdate + ' ' + hours + ':' + minutes + ':' + seconds
    },
    // 计算日期
    // 启动
    showStart(row) {
      this.listLoading = true
      startArticleReading(row).then(res => {
        if (res.data.time < this.timer) {
          this.$notify.warning({
            type: 'warning',
            title: '警告',
            message: '【任务启动时间已过期】需重新设置任务启动时间',
            showClose: true,
            duration: 5 * 1000
          })
        } else {
          this.$notify.success({
            type: 'success',
            title: '成功',
            message: '已启动',
            showClose: true,
            duration: 5 * 1000
          })
        }
        this.getList()
        this.listLoading = false
      })
    },
    // 启动
    // 暂停
    showStop(row) {
      this.listLoading = true
      stopArticleReading(row).then(res => {
        this.$notify.info({
          type: 'success',
          title: '成功',
          message: res.message,
          showClose: true,
          duration: 5 * 1000
        })
        this.getList()
        this.listLoading = false
      })
    },
    // 暂停
    // 删除
    handleDelete(row) {
      this.listLoading = true
      if (row.time < this.timer || row.time === null) {
        delArticleReading(row.id).then(res => {
          this.$notify.info({
            type: 'success',
            title: '删除',
            message: res.message,
            showClose: true,
            duration: 5 * 1000
          })
          this.getList()
          this.listLoading = false
        })
      } else {
        this.$confirm('此操作将移除任务，是否确认？', '删除任务', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          delArticleReading(row.id).then(res => {
            this.$notify.info({
              type: 'success',
              title: '删除',
              message: res.message,
              showClose: true,
              duration: 5 * 1000
            })
            this.getList()
            this.listLoading = false
          })
        }).catch(() => {
          this.$notify.info({
            type: 'info',
            title: '提示',
            message: '已取消删除',
            showClose: true,
            duration: 5 * 1000
          })
        })
      }
    },
    // 删除
    // 颜色状态判断
    tableRowClassName(row) {
      if (row.row.status === '运行中') {
        return 'success-row'
      } else if (row.row.status === '暂停中') {
        return 'warning-row'
      }
      return ''
    }
    // 颜色状态判断
  }
}
</script>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
